package com.meizu.dao;

import com.meizu.entity.Goods;
import com.meizu.utils.Pager;
import com.meizu.utils.RowMapper;
import com.meizu.utils.SQLHelper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
 * 商品列表（分页）的CRUD的DAO类
 * @date 2023/4/19
 **/
public class SearchDao {
    SQLHelper helper=new SQLHelper();

    /**
     * 带条件的分页查询
     * @param pageNo
     * @param pageSize
     * @param pname
     * @param order
     * @return 查询商品名为gname的第pageNo页的结果
     */
    public Pager selectByPager(Integer pageNo,Integer pageSize,String pname,Integer order){
        StringBuilder sql=new StringBuilder("");
        List<Object> param=new ArrayList<>();
        if (pname!=null){
            sql.append(" and gname like concat('%',?,'%') group by a.gname");
            param.add(pname);
        }
        //查询总条数
        Integer total=helper.one("select count(*) from tb_goods where gname like concat('%',?,'%')",
                rs -> {
                    return rs.getInt(1);
                },param.toArray());
        //分页查询
        if (order==0){
            sql.append(" order by b.dprice desc limit ?,?");//降序
        }else{
            sql.append(" order by b.dprice asc limit ?,?");//升序
        }
        param.add((pageNo-1)*pageSize);
        param.add(pageSize);
        List<Goods> list=helper.query("select a.*,b.did,b.dprice from tb_goods a left join tb_detail b on a.gid = b.gid where 1=1 and gstate=1"+sql.toString(),
                new SearchRowMapper(),param.toArray());
        Pager pager =new Pager(pageNo,pageSize);
        pager.setTotal(total);
        pager.setDatas(list);
        return pager;
    }

    class SearchRowMapper implements RowMapper<Goods>{
        @Override
        public Goods map(ResultSet rs) throws SQLException {
            return new Goods(rs.getInt("gid"),
                    rs.getInt("sid"),
                    rs.getString("gname"),
                    rs.getString("gdetail"),
                    rs.getString("gdiscount"),
                    rs.getString("gphoto"),
                    rs.getInt("did"),
                    rs.getBigDecimal("dprice"));
        }
    }
}
